package com.lagou.edu.code.controller;

import com.lagou.edu.code.pojo.LagouAuthCodeParam;
import com.lagou.edu.code.service.LagouAuthCodeService;
import com.lagou.edu.code.service.LagouEmailFeignClient;
import com.lagou.edu.users.pojo.LagouAuthCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 验证码服务，包含创建验证码，校验验证码功能。
 */
@RestController
@RequestMapping("/code")
public class VerificationCodeController {

    @Autowired
    private LagouAuthCodeService lagouAuthCodeService;

    @Autowired
    private LagouEmailFeignClient lagouEmailService;

    /**
     * 生成验证码
     * 1、随机生成4位数字
     * 2、判断该邮箱在指定的时间内是否生成了验证码
     * 4、调用邮件微服务进行邮件发送
     *
     * @param email
     * @return
     */
    @GetMapping("/create/{email}")
    public Boolean create(@PathVariable(name = "email") String email){
        // 1、生成4位数验证码
        String code = lagouAuthCodeService.generateCode();
        // 2、判断该邮箱是否在已经生成了验证码。
        LagouAuthCodeParam param = new LagouAuthCodeParam();
        param.setEmail(email);
        param.setCurrentTime(new Date(System.currentTimeMillis()));
        LagouAuthCode authCodeByEmailAndTime = lagouAuthCodeService.getAuthCodeByEmailAndTime(param);
        // 3、如果已经生成了验证码，将该验证码过期
        if (authCodeByEmailAndTime == null){
            authCodeByEmailAndTime = new LagouAuthCode();
            authCodeByEmailAndTime.setEmail(email);
            authCodeByEmailAndTime.setCode(code);
            lagouAuthCodeService.saveNewAuthCode(authCodeByEmailAndTime);
            lagouEmailService.email(email, code);
        }
        return true;
    }

    /**
     * 校验验证码是否正确
     * @param email 邮箱
     * @param code 验证码
     * @return
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable(name = "email") String email,
                            @PathVariable(name = "code") String code){
        LagouAuthCodeParam param = new LagouAuthCodeParam();
        param.setEmail(email);
        param.setCurrentTime(new Date(System.currentTimeMillis()));
        LagouAuthCode authCodeByEmailAndTime = lagouAuthCodeService.getAuthCodeByEmailAndTime(param);
        if (authCodeByEmailAndTime == null){
            return 2; //超时或者不存在验证码
        }
        if (!authCodeByEmailAndTime.getCode().equals(code)) {
            // 错误验证码
            return 1;
        }
        return 0;
    }

}
